package com.yangmf.auto_message_handle.controller.user;

import com.yangmf.auto_message_handle.constant.CharcConstant;
import com.yangmf.auto_message_handle.constant.JwtClaimsConstant;
import com.yangmf.auto_message_handle.mapper.StudentMapper;
import com.yangmf.auto_message_handle.pojo.dto.CharacterDTO;
import com.yangmf.auto_message_handle.pojo.dto.UserDTO;
import com.yangmf.auto_message_handle.pojo.dto.UserLoginDTO;
import com.yangmf.auto_message_handle.pojo.dto.UserCompleteDTO;
import com.yangmf.auto_message_handle.pojo.entity.Student;
import com.yangmf.auto_message_handle.pojo.entity.User;
import com.yangmf.auto_message_handle.pojo.vo.UserLoginVO;
import com.yangmf.auto_message_handle.pojo.vo.UserVO;
import com.yangmf.auto_message_handle.properties.JwtProperties;
import com.yangmf.auto_message_handle.result.Result;
import com.yangmf.auto_message_handle.service.UserService;
import com.yangmf.auto_message_handle.utils.AliOssUtil;
import com.yangmf.auto_message_handle.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Tag(name = "用户模块")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private StudentMapper studentMapper;

    @PostMapping("/login")
    @Operation(summary = "微信登录")
    public Result<UserLoginVO> login(String code) {
        log.info("微信登录开始");
        UserLoginDTO userLoginDTO = new UserLoginDTO(code);
        User user = userService.wxLogin(userLoginDTO);

        // 添加空值检查
        if (user == null) {
            return Result.error("登录失败，用户信息获取异常");
        }

        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());


        // 生成jwt密钥
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();


        if(user.getSeatNumber()==null)
            userLoginVO.setIs_complete(0L);
        else
            userLoginVO.setIs_complete(1L);


        //查询头像


        return Result.success(userLoginVO);
    }





    @PostMapping("/upload")
    @Operation(summary = "上传用户头像")
    public Result upload(MultipartFile avatar) throws IOException {
        log.info("上传用户头像开始");

        // 添加文件大小校验
        if (avatar.getSize() > 10 * 1024 * 1024) { // 10MB
            return Result.error("文件大小不能超过10MB");
        }

        String url = aliOssUtil.upload(avatar.getBytes(), avatar.getOriginalFilename());
        userService.updateAvatar(url);

        log.info("上传用户头像成功");
        return Result.success();
    }


    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息")
    public Result<UserVO> getUserInfo(){
        log.info("获取用户信息开始");
        UserVO userVO = userService.getUserInfo();
        log.info("获取用户信息成功");
        return Result.success(userVO);
    }

    @PutMapping ("/updateUserInfo")
    @Operation(summary = "更新用户信息")
    public Result updateUserInfo(@RequestBody UserDTO userDTO){
        log.info("更新用户信息开始");
        userService.updateUserInfo(userDTO);
        log.info("更新用户信息成功");
        return Result.success("更新信息成功");
    }

    @GetMapping("/getSeatList")
    @Operation(summary = "获取所有学号")
    public Result getSeatList(){
        log.info("获取所有学号开始");
        return Result.success(userService.getSeatList());
    }

    @PutMapping("/updateCharacter")
    @Operation(summary = "更新用户身份")
    public Result updateCharacter(@RequestBody CharacterDTO character){

        //查询用户身份
        UserVO user = userService.getUserInfo();
        //TODO:权限鉴别
        if(user.getCharacter()!= CharcConstant.CHARACTER_CLASS_LEADER)
            throw new RuntimeException("权限不足");

        log.info("更新用户身份开始");
        userService.updateCharacter(character);
        log.info("更新用户身份成功");
        return Result.success("更新用户身份成功");
    }

    @PutMapping("/completeUserInfo")
    @Operation(summary = "完善用户基本信息")
    public Result completeUserInfo(@RequestBody UserCompleteDTO userCompleteDTO){
        String name = userCompleteDTO.getName();
        log.info("完善用户基本信息开始");
        // 验证姓名不为空
        if (name == null || name.isEmpty())
            return Result.error("姓名不能为空");
        Student studentByName = studentMapper.getStudentByNameAndSeat(userCompleteDTO);
        if(studentByName==null||studentByName.getSeatNumber()==null)
            return Result.error("该用户不存在");
        User userByName = userService.getUserByName(name);
        if(userByName!=null)
            return Result.error("该用户已存在");

        /*
        前端需要实现当返回失败的时候保持弹窗
         */

        userService.completeUserInfo(studentByName);

        log.info("完善用户基本信息成功");
        return Result.success("完善用户基本信息成功");
    }






}